<?php

namespace app\service;

use app\core\Constant;
use app\core\exception\BusinessException;
use app\core\Request;
use app\core\Service;
use app\model\SysPost;
use app\model\SysUserPost;
use think\facade\Db;

/**
 * @extends Service<PostService>
 */
class PostService extends Service
{

    public function selectPosts()
    {
        return SysPost::where('status', Constant::STATUS_NORMAL)
            ->field("post_id, post_name")
            ->select()->toArray();
    }

    public function list($page = 1, $limit = 10, $searchQuery = null)
    {
        $list = SysPost::where(function ($q) use ($searchQuery){
            if (!empty($searchQuery['post_code'])){
                $q = $q->where('post_code', 'like', "%". $searchQuery['post_code'] . "%");
            }
            if (!empty($searchQuery['post_name'])){
                $q = $q->where('post_name', 'like', "%".$searchQuery['post_name']."%");
            }
            if (!empty($searchQuery['status'])){
                $q->where('status', $searchQuery['status']);
            }
        });

        $total = $list->count();
        $list = $list
            ->order('post_sort desc')
            ->page($page, $limit)->select()->toArray();

        return ['total'=>$total,'list'=>$list];
    }

    public function del($post_id)
    {
        $post = SysPost::where('post_id', $post_id)->find();
        if (!$post){
            throw new BusinessException('岗位不存在');
        }

        Db::startTrans();
        try{
            // 删除岗位关联
            SysUserPost::where('post_id', $post_id)->delete();
            $post->delete();
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            throw new BusinessException($e->getMessage());
        }
    }

    public function save($data, $post_id)
    {
        $saveData = [
            'dept_id' => Request::invoke()->getUser('dept_id'),
            'post_code'=>$data['post_code'],
            'post_name'=>$data['post_name'],
            'post_sort'=>$data['post_sort'] ?? 99,
            'status'=>$data['status']  ?? Constant::STATUS_NORMAL,
            'remark'=>$data['remark'] ?? null
        ];

        if (empty($post_id)){
            if (SysPost::where('post_code', $saveData['post_code'])->find()){
                throw new BusinessException('岗位编码已存在');
            }
            $post = SysPost::create($saveData);
            if (empty($post->post_id)){
                throw new BusinessException('创建失败');
            }
        }else{
            $post = SysPost::where('post_id', $post_id)->find();
            if (!$post){
                throw new BusinessException('岗位不存在');
            }
            $post->save($saveData);
        }
    }

    public function info($post_id)
    {
        $post = SysPost::where('post_id', $post_id)->find();
        if (!$post){
            throw new BusinessException('岗位不存在');
        }

        return $post;
    }
}